package com.guit.hrms.service.impl;

import com.guit.hrms.dto.UpdateDTO;
import com.guit.hrms.dto.interview.UpdateInterviewStatusDTO;
import com.guit.hrms.mapper.*;
import com.guit.hrms.po.Employee;
import com.guit.hrms.po.academy.Academy;
import com.guit.hrms.po.otherDept.OtherDept;
import com.guit.hrms.po.position.Position;
import com.guit.hrms.po.resume.EmployeeResume;
import com.guit.hrms.po.resume.EmployeeResumeFile;
import com.guit.hrms.po.resume.WorkExperience;
import com.guit.hrms.service.EmpResumeService;
import com.guit.hrms.service.UpdateService;
import com.guit.hrms.utils.ExcelUtil;
import com.guit.hrms.utils.MD5Util;
import com.guit.hrms.vo.department.DepartmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class UpdateServiceImpl implements UpdateService {
    @Autowired
    private UpdateMapper updateMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private AcademyMapper academyMapper;

    @Autowired
    private OtherDeptMapper otherDeptMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private EmpResumeMapper empResumeMapper;

    @Autowired
    private EmpResumeService empResumeService;
    @Autowired
    private IntervieweeMapper intervieweeMapper;
    @Autowired
    private QueryMapper queryMapper;
    @Autowired
    private OnboardingMapper onboardingMapper;
    @Autowired
    private InterviewMapper interviewMapper;
    @Autowired
    private AttendanceMapper attendanceMapper;
    @Autowired
    private MatterMapper matterMapper;

    /**
     * 修改个人信息
     *
     * @param updateDTO 要修改的员工信息
     * @return 修改结果
     */
    @Override
//    @Transactional
    public Integer updateInfo(UpdateDTO updateDTO) {
        Integer r = updateMapper.updateInfo(updateDTO);
        if (r == 0) {
            throw new RuntimeException("修改失败！");
        } else {
            return r;
//            EmployeeResume employeeResume = new EmployeeResume();
//            employeeResume.setEmployeeId(updateDTO.getEmployeeId());
//            employeeResume.setBasicInfo(new BasicInfo());
//            if (updateDTO.getBirthday() != null) {
//                LocalDate currentDate = LocalDate.from(updateDTO.getBirthday());
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");
//                String formattedDate = currentDate.format(formatter);
//                employeeResume.getBasicInfo().setBirthDate(formattedDate);
//            }
//            if (updateDTO.getPhoneNumber() != null) {
//                employeeResume.getBasicInfo().setPhone(updateDTO.getPhoneNumber());
//            }
//            if (updateDTO.getEmail() != null) {
//                employeeResume.getBasicInfo().setEmail(updateDTO.getEmail());
//            }
//            System.out.println(employeeResume.getBasicInfo().toString());
//            Integer result = empResumeService.updateEmpResume(employeeResume);
//            if (result == 0) {
//                throw new RuntimeException("修改失败！");
//            } else {
//                return result;
//            }
        }
    }

    /**
     * 管理员修改员工信息
     *
     * @param updateDTO 要修改的员工信息
     * @return 修改结果
     */
    @Transactional
    @Override
    public Integer updateProfile(UpdateDTO updateDTO) {
        DepartmentVO departmentVO = null;
        Academy academy = null;
        OtherDept otherDept = null;
        Position position = null;
        String departmentName = null;
        String positionName = null;
        Integer r1 = 0;
        Employee employee = updateMapper.getById(updateDTO.getEmployeeId());
        if (employee == null) {
            throw new RuntimeException("该员工不存在！");
        }
        if (updateDTO.getStatus() == 2) {
            r1 = updateMapper.updateProfile(updateDTO);
            if (r1 == 0) {
                System.out.println(updateDTO);
                throw new RuntimeException("修改失败！请确定信息该员工工号正确！");
            } else {
                UpdateInterviewStatusDTO updateInterviewStatusDTO = new UpdateInterviewStatusDTO();
                List<Integer> interviewIds = new ArrayList<>();
                interviewIds.add(employee.getIntervieweeId());
                updateInterviewStatusDTO.setIntervieweeIds(interviewIds);
                updateInterviewStatusDTO.setInterviewStatus(10);
                r1 = intervieweeMapper.updateInterviewStatus(updateInterviewStatusDTO);
                if (r1 == 0) {
                    throw new RuntimeException("修改员工对应的应聘者状态失败");
                }
                EmployeeResume employeeResume = new EmployeeResume();
                employeeResume.setEmployeeId(updateDTO.getEmployeeId());

                LocalDate currentDate = LocalDate.now();

                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");

                String formattedDate = currentDate.format(formatter);

                WorkExperience workExperience = new WorkExperience("", "", formattedDate, "离职");
                employeeResume.setWorkExperiences(Collections.singletonList(workExperience));

                Integer result = empResumeService.addEmpResumeMsg(employeeResume);
                if (result == 0) {
                    throw new RuntimeException("新增员工履历记录失败");
                } else {
                    return 1;
                }
            }
        }
        if (updateDTO.getRoleId() != null) {
            if (roleMapper.getRoleById(updateDTO.getRoleId()) != null) {
                r1 = updateMapper.updateRole(updateDTO);
            } else {
                throw new RuntimeException("角色不存在！");
            }
            if (r1 == 0) {
                throw new RuntimeException("修改角色失败！");
            }
        }
        if ((((updateDTO.getDepartment() != null && updateDTO.getDepartment() != 0)
                && (updateDTO.getPosition() != null && updateDTO.getPosition() != 0))
                && (updateDTO.getDeptType() != null && updateDTO.getDeptType() != 0))) {
            if (updateDTO.getDeptType() == 1) {
                departmentVO = departmentMapper.selectDepartmentById(updateDTO.getDepartment());
                position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
            } else if (updateDTO.getDeptType() == 2) {
                academy = academyMapper.getAcademyById(updateDTO.getDepartment());
                position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
            } else if (updateDTO.getDeptType() == 3) {
                otherDept = otherDeptMapper.getOtherDeptById(updateDTO.getDepartment());
                position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
            } else {
                throw new RuntimeException("部门类型错误");
            }
            if ((departmentVO == null && academy == null && otherDept == null) || position == null) {
                throw new RuntimeException("部门或岗位不存在");
            } else {
                if (departmentVO != null) {
                    departmentName = departmentVO.getDeptName();
                } else if (academy != null) {
                    departmentName = academy.getAcademyName();
                } else {
                    departmentName = otherDept.getOtherDeptName();
                }
                positionName = position.getPositionName();
            }
            r1 = updateMapper.updateProfile(updateDTO);
        } else if ((((updateDTO.getDepartment() == null) && (updateDTO.getDeptType() == null))
                && (updateDTO.getPosition() != null && updateDTO.getPosition() != 0))) {
            position = positionMapper.getPositionById(updateDTO.getPosition(), employee.getDeptType(), employee.getDepartment());
            if (position == null) {
                throw new RuntimeException("岗位不存在");
            } else {
                positionName = position.getPositionName();
            }
            r1 = updateMapper.updateProfile(updateDTO);
        } else if ((updateDTO.getDepartment() != null && (updateDTO.getPosition() == null || updateDTO.getDeptType() == null))
                || (updateDTO.getPosition() != null && (updateDTO.getDepartment() == null || updateDTO.getDeptType() == null))
                || (updateDTO.getDeptType() != null && (updateDTO.getDepartment() == null || updateDTO.getPosition() == null))) {
            throw new RuntimeException("部门或岗位修改信息不完整");
        }

        if (r1 == 0) {
            System.out.println(updateDTO.toString());
            throw new RuntimeException("修改失败！");
        } else {
            if (updateDTO.getStatus() == 1) {
                UpdateInterviewStatusDTO updateInterviewStatusDTO = new UpdateInterviewStatusDTO();
                List<Integer> interviewIds = new ArrayList<>();
                interviewIds.add(employee.getIntervieweeId());
                updateInterviewStatusDTO.setIntervieweeIds(interviewIds);
                updateInterviewStatusDTO.setInterviewStatus(9);
                r1 = intervieweeMapper.updateInterviewStatus(updateInterviewStatusDTO);
                if (r1 == 0) {
                    throw new RuntimeException("修改员工对应的应聘者状态失败");
                }
            }

            EmployeeResume employeeResume = new EmployeeResume();
            employeeResume.setEmployeeId(updateDTO.getEmployeeId());

            LocalDate currentDate = LocalDate.now();

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");

            String formattedDate = currentDate.format(formatter);

            WorkExperience workExperience = new WorkExperience(/*"桂林信息科技学院"+*/departmentName, positionName, formattedDate, updateDTO.getStatus() == null ? "转岗" : "转正");
            employeeResume.setWorkExperiences(Collections.singletonList(workExperience));

            Integer result = empResumeService.addEmpResumeMsg(employeeResume);
            if (result == 0) {
                throw new RuntimeException("新增员工履历记录失败");
            } else {
                return 1;
            }
        }
    }

    /**
     * 员工修改密码
     *
     * @param updateDTO 修改前后的密码
     * @return 修改结果
     */
    @Override
    public Integer updatePwd(UpdateDTO updateDTO) {
        String employeeId = updateDTO.getEmployeeId();
        Employee employee = updateMapper.getById(employeeId);
        String password = employee.getPassword();
        String oldPassword = MD5Util.encrypt(updateDTO.getOldPassword());
        String newPassword = MD5Util.encrypt(updateDTO.getNewPassword());
        if (!password.equals(oldPassword)) {
            return 0;
        }
        updateMapper.updatePassword(employeeId, newPassword);
        return 1;
    }

    /**
     * 管理员重置员工密码
     *
     * @param employeeId  要重置密码的员工工号
     * @param newPassword 新的密码
     * @return 修改结果
     */
    @Override
    public Integer resetPwd(String employeeId, String newPassword) {
        newPassword = MD5Util.encrypt(newPassword);
        return updateMapper.updatePassword(employeeId, newPassword);
    }

    /**
     * 新增员工信息
     *
     * @param updateDTO 要新增的员工信息
     */
    @Override
    @Transactional
    public Integer insertInfo(UpdateDTO updateDTO) {
        DepartmentVO departmentVO = null;
        Academy academy = null;
        OtherDept otherDept = null;
        Position position = null;
        String departmentName = null;
        String positionName = null;
        Integer r1 = 0;

        if (updateDTO.getRoleId() == null) {
            return 0;
        } else {
            if (roleMapper.getRoleById(updateDTO.getRoleId()) != null) {
                r1 = updateMapper.insertRole(updateDTO);
            } else {
                throw new RuntimeException("角色不存在！");
            }
            if (r1 == 0) {
                throw new RuntimeException("修改角色失败！");
            }
        }
        String employeeId = updateDTO.getEmployeeId();

        updateDTO.setPassword(MD5Util.encrypt("123456"));

        Employee byId = updateMapper.getById(employeeId);
        if (byId != null) {
            return 2;
        }

        if (updateDTO.getDeptType() == 1) {
            departmentVO = departmentMapper.selectDepartmentById(updateDTO.getDepartment());
            position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
        } else if (updateDTO.getDeptType() == 2) {
            academy = academyMapper.getAcademyById(updateDTO.getDepartment());
            position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
        } else if (updateDTO.getDeptType() == 3) {
            otherDept = otherDeptMapper.getOtherDeptById(updateDTO.getDepartment());
            position = positionMapper.getPositionById(updateDTO.getPosition(), updateDTO.getDeptType(), updateDTO.getDepartment());
        } else {
            throw new RuntimeException("部门类型错误");
        }
        if ((departmentVO == null && academy == null && otherDept == null) || position == null) {
            throw new RuntimeException("部门或岗位不存在");
        } else {
            if (departmentVO != null) {
                departmentName = departmentVO.getDeptName();
            } else if (academy != null) {
                departmentName = academy.getAcademyName();
            } else {
                departmentName = otherDept.getOtherDeptName();
            }
            positionName = position.getPositionName();
        }

        r1 = updateMapper.insertInfo(updateDTO);
        if (r1 == 0) {
            throw new RuntimeException("新增失败");
        } else {
            EmployeeResume employeeResume = new EmployeeResume();
            employeeResume.setEmployeeId(employeeId);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");

            String formattedDate = updateDTO.getBirthday().format(formatter);

//            employeeResume.setBasicInfo(updateDTO.getUsername(), updateDTO.getGender() == 1 ? "男" : "女" , formattedDate, updateDTO.getPhoneNumber(), updateDTO.getEmail());

            LocalDate currentDate = LocalDate.now();

            formatter = DateTimeFormatter.ofPattern("yyyy年M月d日");

            formattedDate = currentDate.format(formatter);

            WorkExperience workExperience = new WorkExperience("桂林信息科技学院" + departmentName, positionName, formattedDate, "入职");
            employeeResume.setWorkExperiences(Collections.singletonList(workExperience));

            try {
                EmployeeResumeFile employeeResumeFile = ExcelUtil.createResumeExcel(employeeResume);
                employeeResumeFile.setEmployeeId(employeeId);
                employeeResumeFile.setFileName(employeeId + updateDTO.getUsername() + "的履历");
                employeeResumeFile.setUpdatedAt(LocalDateTime.now());
                Integer result = empResumeMapper.createEmpResume(employeeResumeFile);
                if (result == 0) {
                    throw new RuntimeException("新增失败");
                } else {
                    return 1;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 管理员删除员工
     *
     * @param employeeIds 要删除的员工工号
     * @return 删除结果
     */
    @Transactional
    @Override
    public Integer deleteById(List<String> employeeIds) {
        Integer result = 0;
        List<Employee> employees = new ArrayList<>();
        Employee employee = null;
        for (String employeeId : employeeIds) {
            employee = queryMapper.getById(employeeId);
            if (employee == null) {
                throw new RuntimeException("员工不存在!请确保员工工号正确！");
            }
            employees.add(employee);
        }
        employeeIds.forEach(employeeId -> {
            attendanceMapper.deleteEmpSignByEmployeeId(employeeId);
            attendanceMapper.deleteStatisticsByEmployeeId(employeeId);
            matterMapper.deleteMatterByEmployeeId(employeeId);
            attendanceMapper.deleteTransactionByEmployeeId(employeeId);
        });

        employees.forEach(employee1 -> {
            if (interviewMapper.deleteInterviewSituationByIntervieweeId(employee1.getIntervieweeId()) == 0) {
                throw new RuntimeException("删除员工为应聘者时的面试情况失败");
            }
            if (intervieweeMapper.deleteInterviewee(employee1.getIntervieweeId()) == 0) {
                throw new RuntimeException("删除员工的应聘者信息失败");
            }
            if (intervieweeMapper.deleteOfferByIntervieweeId(employee1.getIntervieweeId()) == 0) {
                throw new RuntimeException("删除员工为应聘者的offer信息失败");
            }
            if (onboardingMapper.deleteOnboardingByIntervieweeId(employee1.getIntervieweeId()) == 0) {
                throw new RuntimeException("删除员工为应聘者的入职信息失败");
            }
            if (positionMapper.updatePositionPersonById(employee1.getPosition(), 1) == 0) {
                throw new RuntimeException("更新员工原职位人数失败");
            }
        });

        result = updateMapper.deleteById(employeeIds);
        if (result == 0) {
            throw new RuntimeException("删除员工信息失败");
        }
        result = updateMapper.deleteEmpRole(employeeIds);
        if (result == 0) {
            throw new RuntimeException("删除员工角色失败");
        }
        for (String employeeId : employeeIds) {
            result = empResumeMapper.deleteEmpResume(employeeId);
            if (result == 0) {
                throw new RuntimeException("删除员工履历失败");
            }
        }
        return 1;
    }

    /**
     * 管理员解绑员工微信
     * @param employeeId 要解绑的员工工号
     * @return 解绑结果
     */
    @Override
    public Integer resetWx(String employeeId) {
        return updateMapper.resetWx(employeeId);
    }
}
